package com.chinasoft.mall.framework;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.chinasoft.mall.framework.abs.RequestCallback;
import com.chinasoft.mall.model.BaseBean;
import com.chinasoft.mall.model.DownloadInfo;
import com.chinasoft.mall.model.response.BaseResponse;
import com.chinasoft.mall.model.response.EpgBean;
import com.chinasoft.mall.model.response.GetGameBean;
import com.chinasoft.mall.model.response.GetGameBean.Data;
import com.chinasoft.mall.model.response.RechnBean;
import com.chinasoft.mall.receiver.myBroadCast;
import com.chinasoft.mall.util.SystemUtil;
import com.chinasoft.mall.widget.dialog.ShowProgressDialog;

/**
 * 控制器
 * 
 * @author Administrator
 */
@SuppressLint("HandlerLeak")
public class ControllerCenter implements RequestCallback
{

	

	
	private static ControllerCenter cc = new ControllerCenter();
	private static Successcallback successcallback;
	private static Failcallback failcallback;
	private Processor _processor;

	private static Context myContext;

	private static ShowProgressDialog spd;
	private static BlockingQueue<Message> messageQuene = new ArrayBlockingQueue<Message>(
			100);
	private Thread t;

	public Context getMyContext()
	{
		return myContext;
	}

	public void setMyContext(Context myContext)
	{
		ControllerCenter.myContext = myContext;
		if (myContext != null)
		{
			if (spd != null && spd.isShowing())
			{
				spd.dismiss();
			}
			spd = new ShowProgressDialog(myContext, "正在加载");
			spd.setOnCancelListener(_processor);
		}

	}

	public void clear()
	{
		spd = null;
	}

	public static void LoadingDialog()
	{
		if (spd != null)
		{
			spd.show();
		}
	}

	public static void LoadOverDialog()
	{
		if (spd != null)
		{
			spd.dismiss();
		}
	}

	public static Failcallback getFailcallback()
	{
		return failcallback;
	}

	public void setFailcallback(Failcallback failcallback)
	{
		ControllerCenter.failcallback = failcallback;
	}

	public void setSuccesscallback(Successcallback uicallback)
	{
		ControllerCenter.successcallback = uicallback;
	}

	public static Successcallback getSuccesscallback()
	{
		return successcallback;
	}

	public static Handler myhandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			if (msg.obj instanceof BaseBean)
			{
				// 取消进度框
				LoadOverDialog();

				// if (BaseActivity.baseActivity != null) {
				// BaseActivity.baseActivity.LoadOver();
				// }
				Log.i("BROADCAST_TAG", "myContext" + myContext + "//;");
				if (myContext != null)
					Log.i("BROADCAST_TAG",
							"isAppNow:"
									+ SystemUtil.isAppOnForeground(myContext));
				if (myContext == null
						|| SystemUtil.isAppOnForeground(myContext))
				{
					if (successcallback != null
							&& Config.VerfityStatus(cc.getMyContext(),
									(BaseBean) msg.obj))
					{
						successcallback.success((BaseBean) msg.obj);
					}
					else if (failcallback != null)
					{
						failcallback.fail((BaseBean) msg.obj);
					}
				}
				// 后台弹出提示
				else if (myContext != null)
				{
					Log.i("BROADCAST_TAG", "匹配数据//;");
					if (Config.GET_GAME.equals(((BaseBean) msg.obj)
							.getReq_url()))
					{
						if (((BaseBean) msg.obj).getResData() != null
								&& ((BaseBean) msg.obj).getResData().getData() != null)
						{
							GetGameBean _ggb = ((GetGameBean) ((BaseBean) msg.obj)
									.getResData().getData());
							List<Data> lds = _ggb.getDatas();
							EpgBean _eb = new EpgBean();
							if (_ggb.getContent() != null
									&& !"".equals(_ggb.getContent())
									&& !OrderGoods.prompt_bg.contains(_ggb
											.getContent()))
							{
								_eb.setTHUM(_ggb.getContent());
								OrderGoods.prompt_bg.add(_ggb.getContent());
								Intent intent = new Intent(
										myBroadCast.ACTION_INTENT_TEST);
								intent.putExtra(Config.INTENT_OBJ, _eb);
								myContext.sendBroadcast(intent);
							}
							if (lds != null && lds.size() > 0)
							{
								for (Data d : lds)
								{
									if (!OrderGoods.goodsids_bg.contains(d))
									{
										OrderGoods.goodsids_bg.add(d);
										// OrderGoods.isCancle
										// =
										// true;
										_eb.setGOODS_NAME(d.getGoodsName());
										_eb.setBiType((byte) 1);
										Intent intent = new Intent(
												myBroadCast.ACTION_INTENT_TEST);
										intent.putExtra(Config.INTENT_OBJ, _eb);
										myContext.sendBroadcast(intent);
										break;
									}
								}
							}
						}

					}
				}
			}
		}
	};

	private ControllerCenter()
	{
		_processor = Processor.getInstance();
		if (t == null)
		{
			t = new Thread()
			{

				@Override
				public void run()
				{
					super.run();
					while (true)
					{
						// myhandler.sendMessage(message);

						try
						{
							Thread.sleep(500);
						}
						catch (InterruptedException e1)
						{
							// TODO Auto-generated
							// catch block
							e1.printStackTrace();
						}
						Message message = null;
						try
						{
							message = messageQuene.take();
						}
						catch (InterruptedException e)
						{
							e.printStackTrace();
							continue;
						}
						if (message == null)
						{
							continue;
						}
						myhandler.sendMessage(message);
					}
				}
			};
		}
		t.start();
	}

	public static ControllerCenter getInstance()
	{
		return cc;
	}

	public void sendMessage(BaseBean tm)
	{
		// 加载进度框
		LoadingDialog();

		// if (BaseActivity.baseActivity != null) {
		// BaseActivity.baseActivity.Loading();
		// }
		tm.setRc(this);
		_processor.startMission(tm);
	}

	// 静默发送请求
	public void postMessage(BaseBean tm)
	{
		tm.setRc(this);
		_processor.startMission(tm);
	}

	@Override
	public void Centercall(BaseBean obj)
	{
		if (obj.getStatus() == 0)
		{
			if (obj.isAdd())
			{
				BeanCache.getInstance().getResponsdata().put(obj.getReq_url(), obj);
				Log.e("rechbean ",
						"put date "
								+ obj.getReq_url());
				if (obj.getReq_url().equals(Config.GET_RECHN))
				{
					Log.e("jingji qingkuag", "jingji qingkuag");
					BeanCache.getBottomCache().clear();
					ArrayList<RechnBean> tmp = (ArrayList<RechnBean>) obj.getResData().getData();
					for(RechnBean rechBean : tmp)
					{
						BeanCache.getBottomCache().add(rechBean);
					}
				}

			}
		}
		Message message = new Message();
		message.obj = obj;
		try
		{
			messageQuene.put(message);
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}

	}

	/**
	 * 成功监听
	 * 
	 * @author Administrator
	 */
	public static interface Successcallback
	{
		public void success(BaseBean obj);
	}

	/**
	 * 失败监听
	 * 
	 * @author Administrator
	 */
	public static interface Failcallback
	{
		public void fail(BaseBean obj);
	}

}
